<?php

namespace yunj\validate;

use think\File;
use yunj\Validate;

class YunjUpload extends Validate {

    protected $rule = [
        'file' => 'require',
    ];

    protected $message = [
        'file.require' => '未找到上传的文件(文件大小可能超过php.ini限制)！',
    ];

    protected $scene = [
        'file' => ['file'],
    ];

    protected function handleData(array $raw_data, $scene): array {
        $data = $raw_data;
        switch ($scene) {
            case 'file':
                $data = $this->handleDataByFile($data);
                break;
        }
        return $data;
    }

    private function handleDataByFile($raw_data) {
        $data = $raw_data;

        $file = $data['file'];
        if (!($file instanceof File)) throw_error_json('文件异常！');
        // 文件MIME类型
        $mime = $file->getMime();
        if ($mime == 'text/x-php' || $mime == 'text/html') throw_error_json('禁止上传php,html文件！');
        // 格式
        $res = $file->checkExt('pdf,xlsx,xls,csv');
        if (!$res) throw_error_json('非系统允许的上传格式！');
        // 大小
        $res = $file->checkSize(1024 * 1024);
        if (!$res) throw_error_json('上传文件超过系统限制1024KB！');
        //文件路径
        $filePath = "/upload/file/";
        //文件上传路径
        $uploadFilePath = env('root_path') . 'public' . $filePath;
        //返回数据
        $data = [
            'type' => 'file',
            'file_path' => $filePath,
            'upload_file_path' => $uploadFilePath,
            'file' => $file
        ];
        return $data;
    }
}